﻿using System;
using System.ComponentModel;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	public abstract class MyFormatBaseValidator : System.Web.UI.WebControls.RegularExpressionValidator {
		private bool m_initialized = false;

		/// <summary>
		/// 
		/// </summary>
		protected virtual void UpdateErrorMessage() {
			if (m_initialized) {
				ErrorMessage = string.Format(Properties.Main.ErrorInvalidFormat, PropertyTitle);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(true)]
		[Browsable(true)]
		[DefaultValue("")]
		public string PropertyTitle {
			get {
				var obj = ViewState["PropertyTitle"];

				return obj == null ? "" : (string)obj;
			}
			set {
				ViewState["PropertyTitle"] = value;

				UpdateErrorMessage();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected abstract string GetExpression();

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
			SetFocusOnError = true;

			if (string.IsNullOrEmpty(ValidationExpression)) {
				ValidationExpression = string.Concat(@"^\s*", GetExpression(), @"\s*$");
			}

			m_initialized = true;
			if (string.IsNullOrWhiteSpace(ErrorMessage)) {
				UpdateErrorMessage();
			}
		}
	} // end of MyFormatBaseValidator.
}
